package com.xbongbong.pro.aiassistant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.aiassistant.manager.feign.BusinessFeignClient;
import com.xbongbong.pro.aiassistant.service.GenerateDataService;
import com.xbongbong.pro.constant.AiAssistantConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.smartsettings.pojo.SsTimeAndExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.dto.GenerateDataDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.GetHistoryDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsUpdateBatchDTO;
import com.xbongbong.pro.smartsettings.pojo.vo.GetHistoryVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsUpdateBatchVO;
import com.xbongbong.pro.sms.pojo.SmsReceiverPojo;
import com.xbongbong.pro.sms.pojo.dto.SmsRabbitMqDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.BomProductEntity;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.OpportunityStageLogEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.domain.entity.SpecificationEntity;
import com.xbongbong.saas.domain.entity.ext.BomBillEntityExt;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.ContractProduceEnum;
import com.xbongbong.saas.enums.ContractProductTypeEnum;
import com.xbongbong.saas.enums.SmsSendTypeEnum;
import com.xbongbong.saas.enums.SmsTemplateSendApiEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.model.AiAssistantHistoryModel;
import com.xbongbong.saas.model.AiAssistantModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.BomProductModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityStageLogModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.StageWorkModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @Author: hongxiao
 * @date: 2019-11-28 08:44
 */
@Service("generateDataService")
public class GenerateDataServiceImpl implements GenerateDataService {
    private static Logger LOG = LoggerFactory.getLogger(GenerateDataServiceImpl.class);

    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private BusinessFeignClient businessFeignClient;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private BomProductModel bomProductModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private AiAssistantModel aiAssistantModel;
    @Resource
    private AiAssistantHistoryModel aiAssistantHistoryModel;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private OpportunityStageLogModel opportunityStageLogModel;
    @Resource
    private StageWorkModel stageWorkModel;

    @Override
    public String testSms(String corpid, String receiveUserId, Long id, List<Long> dataIds, Integer businessType) {

        String content = "【销帮帮】 test服务已经完成，张杰 邀请你对本次服务进行评价，谢谢你选择我们的服务。";
        List<SmsReceiverPojo> receiverPojoList = new ArrayList<>();
        SmsReceiverPojo smsReceiverPojo = new SmsReceiverPojo();
        smsReceiverPojo.setName("刘先生");
        smsReceiverPojo.setPhone("13643806682");
        receiverPojoList.add(smsReceiverPojo);

        SmsRabbitMqDTO smsRabbitMqDTO = new SmsRabbitMqDTO();
        smsRabbitMqDTO.setCorpid(corpid);
        // 系统生成
        smsRabbitMqDTO.setUserId(PaasConstant.SYS_USER_ID);
        smsRabbitMqDTO.setSendType(SmsSendTypeEnum.AT_ONCE.getCode());
        // 尊称无法传递，直接替换
        smsRabbitMqDTO.setContent(content);
        // 短信发送API类型
        smsRabbitMqDTO.setSendApi(SmsTemplateSendApiEnum.SPACE_IMAGINATION_NOTICE_AMOUNT.getCode());
//        smsRabbitMqDTO.setDates(null);
        smsRabbitMqDTO.setSendData(receiverPojoList);
        try {
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            String sendData = businessFeignClient.smsSend(smsRabbitMqDTO, lang);
            JSONObject resultObj = JsonHelperUtil.parseObject(sendData);
            if (ErrorCodeEnum.API_SUCCESS.getCode() != (int)resultObj.get(StringConstant.CODE)) {
                throw new XbbException(resultObj.getIntValue(StringConstant.CODE),resultObj.getString(StringConstant.KEY_ERROR_MSG));
            }
        } catch (XbbException e) {
            e.printStackTrace();
        }

        return "操作成功";
    }

    @Override
    public String testCommunicatePlan(String corpid, String receiveUserId, Long id, List<Long> dataIds, Integer businessType) {
        // id: 293～318

        // 客户id
        Long customerId = id;
        CustomerEntityExt customerEntityExt = customerModel.getByKey(id, corpid);

        // 执行人
        List<UserEntity> userEntitys = new ArrayList<>();
        UserEntity userEntity = userModel.getByKey(receiveUserId, corpid);
        userEntitys.add(userEntity);

        JSONObject communicatePlan = new JSONObject();
        JSONObject customerData = customerEntityExt.getData();
        String customerName = customerData.getString(CustomerManagementEnum.NAME.getAttr());
        communicatePlan.put(CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), customerId);
        communicatePlan.put(CommunicatePlanEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), customerName);

        PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), corpid);
        Long sendTime = DateTimeUtil.getInt("2019-11-28 19:00", DateTimeUtil.SDFYMDHM);
        try {
            List<String> executorTypeList = Arrays.asList("2");
            communicatePlan.put(CommunicatePlanEnum.EXECUTOR.getAttr(), executorTypeList);
            communicatePlan.put(CommunicatePlanEnum.NOTIFY_TYPE.getAttr(), "0");
            // 访客计划执行时间
            communicatePlan.put(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr(), sendTime);
            communicatePlan.put(CommunicatePlanEnum.NAME.getAttr(), I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE));
            communicatePlan.put(CommunicatePlanEnum.MEMO.getAttr(), I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE_MEMO));
            // TODO 访客计划备注以及名称不确定
            CommunicatePlanEntityExt communicatePlanEntityExt = new CommunicatePlanEntityExt();
            BeanUtil.copyProperties(paasFormEntity, communicatePlanEntityExt);
            communicatePlanEntityExt.setFormId(paasFormEntity.getId());
            communicatePlanEntityExt.setData(communicatePlan);
            communicatePlanEntityExt.setDel(BasicConstant.ZERO);
            communicatePlanEntityExt.setId(null);
            communicatePlanEntityExt.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            // 创建人
            communicatePlanEntityExt.setCreatorId(PaasConstant.SYS_USER_ID);
            // 负责人
            communicatePlanEntityExt.setOwnerId(PaasConstant.SYS_USER_ID);
            communicatePlanEntityExt.setSerialNo("");
            communicatePlanEntityExt.setDepartmentId(0L);
            communicatePlanModel.insert(communicatePlanEntityExt);

            // 保存执行人
            List<CommunicatePlanUserEntity> planUserList = new ArrayList<>();
            for (UserEntity user : userEntitys) {
                CommunicatePlanUserEntity planUser = new CommunicatePlanUserEntity();
                planUser.setCorpid(corpid);
                planUser.setDataId(communicatePlanEntityExt.getId());
                planUser.setUserId(user.getUserId());
                planUser.setUserName(user.getName());
                planUser.setUserAvatar(user.getAvatar());
                planUser.setIsCreator(BasicConstant.ZERO);
                planUserList.add(planUser);

            }
            communicatePlanUserModel.insertBatch(planUserList);

        } catch (Exception e) {
            // 报错
            e.printStackTrace();
        }

        return "操作成功";
    }

    @Override
    public SmartSettingsUpdateBatchVO updateBatch(SmartSettingsUpdateBatchDTO updateBatchDTO) throws XbbException {
        SmartSettingsUpdateBatchVO updateBatchVO = new SmartSettingsUpdateBatchVO();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, updateBatchDTO.getCorpid());
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("idIn", updateBatchDTO.getIds());
        List<AiAssistantEntity> list = aiAssistantModel.findEntitys(param);

        if (Objects.isNull(list) || list.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, SystemErrorCodeEnum.API_ERROR_100018.getMsg());
        }

        // 执行策略
        JSONObject strategy = null;
        if (Objects.nonNull(updateBatchDTO.getStrategy())) {
            String strategyStr = JSON.toJSONString(updateBatchDTO.getStrategy());
            strategy = JsonHelperUtil.parseObject(strategyStr);
        }
        // 执行人
        JSONArray executor = null;
        if (Objects.nonNull(updateBatchDTO.getExecutor())) {
            executor = new JSONArray();
            executor.addAll(updateBatchDTO.getExecutor());
        }

        for (AiAssistantEntity entity : list) {
            entity.setEnable(updateBatchDTO.getEnable());
            entity.setAction(updateBatchDTO.getAction());
            entity.setStrategy(strategy);
            entity.setExecutor(executor);
        }

        try {
            aiAssistantModel.updateBatch(list, updateBatchDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("智能助手批量更新失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return updateBatchVO;
    }

    @Override
    public GetHistoryVO getHistory(GetHistoryDTO getHistoryDTO) throws XbbException {
        GetHistoryVO getHistoryVO = new GetHistoryVO();

        String corpid = getHistoryDTO.getCorpid();

        List<String> timeSpan = getHistoryDTO.getTimeSpan();
        Integer startTime = DateUtil.getInt(timeSpan.get(0), DateUtil.SDFDate);
        Integer endTime;
        if (timeSpan.size() == BasicConstant.TWO) {
            endTime = DateUtil.getInt(timeSpan.get(1), DateUtil.SDFDate);
        } else {
            endTime = startTime + TimeConstant.SECONDS_PER_DAY;
        }

        Double dayNum = Arith.div(Math.abs(endTime - startTime), TimeConstant.SECONDS_PER_DAY);

        if (dayNum > 10D) {
           throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "查询区间不能超过10天");
        }

        List<AiAssistantHistoryEntity> historyList = new ArrayList<>();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());

        param.put("aiAssistantId", getHistoryDTO.getAiAssistantId());
        param.put("startTriggerTime", startTime);
        param.put("endTriggerTime", endTime);

        int count = aiAssistantHistoryModel.getEntitysCount(param);
        int start = 0;
        int pageNum = 2000;

        for (; start <= count; start = start + pageNum) {
            param.put("start", start);
            param.put("pageNum", pageNum);
            List<AiAssistantHistoryEntity> list = aiAssistantHistoryModel.findEntitys(param);
            historyList.addAll(list);
        }


        if (Objects.nonNull(historyList) && !historyList.isEmpty()) {
            List<Map<String, Object>> historyMapList = new ArrayList<>();
            for (AiAssistantHistoryEntity entity : historyList) {
                Map<String, Object> historyMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<SsTimeAndExecutorPojo> timeAndExecutorList = entity.getTimeAndExecutor().toJavaList(SsTimeAndExecutorPojo.class);
                for (SsTimeAndExecutorPojo pojo : timeAndExecutorList) {
                    String day = DateUtil.getString(pojo.getTime() * 1000, DateUtil.SDFDate);
                    pojo.setDay(day);
                }
                historyMap.put("dataId", entity.getDataId());
                historyMap.put("executorList", timeAndExecutorList);
                historyMapList.add(historyMap);
            }
            getHistoryVO.setList(historyMapList);
        }


        return getHistoryVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String generateData(GenerateDataDTO generateDataDTO) throws XbbException {
        String returnStr = "";
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(generateDataDTO.getBusinessType());

        // 生成的数据量
        Long dataSize = generateDataDTO.getDataSize() == null ? AiAssistantConstant.DEFAULT_DATA_SIZE : generateDataDTO.getDataSize();
        if (dataSize <= 0) {
            dataSize = AiAssistantConstant.DEFAULT_DATA_SIZE;
        }
        long nowTime = DateUtil.getInt();

        // 数据的添加时间，更新时间
        long addTime = generateDataDTO.getAddTime() == null ? nowTime : nowTime + generateDataDTO.getAddTime() * TimeConstant.SECONDS_PER_DAY;
        long updateTime = generateDataDTO.getUpdateTime() == null ? nowTime : nowTime + generateDataDTO.getUpdateTime() * TimeConstant.SECONDS_PER_DAY;

        switch (refTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                returnStr = generateCustomerData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case SALES_OPPORTUNITY:
                returnStr = generateOpportunityData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case CONTRACT:
                returnStr = generateContractData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case PAYMENT:
                returnStr = generatePaymentData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case PAY_PLAN:
                returnStr = generatePayPlanData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case SUPPLIER:
                returnStr = generateSupplierData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case PURCHASE:
                returnStr = generatePurchaseData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case PRODUCTION_ORDER:
                returnStr = generateProductionOrderData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case PRODUCT:
                returnStr = generateProductData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case WAIT_PURCHASE:
                returnStr = generateWaitPurchaseData(generateDataDTO, dataSize, addTime, updateTime, nowTime,ContractProduceEnum.WAIT_PURCHASE.getCode());
                break;
            case WAIT_PRODUCE:
                returnStr = generateWaitPurchaseData(generateDataDTO, dataSize, addTime, updateTime, nowTime,ContractProduceEnum.WAIT_PRODUCE.getCode());
                break;
            case WAIT_OUTSTOCK:
                returnStr = generateWaitOutstockData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            case WAIT_INSTOCK_PURCHASE:
                returnStr = generateWaitInstockData(generateDataDTO, dataSize, addTime, updateTime, nowTime);
                break;
            default:
                break;
        }
        return returnStr;
    }

    private String generateWaitInstockData(GenerateDataDTO generateDataDTO, Long dataSize, long addTime, long updateTime, long nowTime) throws XbbException {
        String corpid = generateDataDTO.getCorpid();
        PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(generateDataDTO.getDataId(),corpid);
        if (Objects.isNull(purchaseEntityExt)) {
            return "dataId对应的采购合同不存在";
        }

        List<PurchaseEntityExt> insertList = new ArrayList<>();
        for (int i = 0;i <dataSize;i++){
            PurchaseEntityExt entityExt = new PurchaseEntityExt();
            BeanUtil.copyProperties(purchaseEntityExt,entityExt);
            entityExt.setId(null);
            entityExt.setAddTime(addTime);
            entityExt.setUpdateTime(updateTime);
            purchaseModel.insert(entityExt);
            insertList.add(entityExt);
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery("del",0));
        boolQueryBuilder.filter(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID),generateDataDTO.getProductId()));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ProductEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,ProductEntityExt.class);
        ProductEntityExt productEntityExt = esEntities.getContent().get(0);
        PurchaseProductEntity purchaseProductEntity = new PurchaseProductEntity();
        purchaseProductEntity.setCorpid(corpid);
        purchaseProductEntity.setProductNum(1D);
        purchaseProductEntity.setProductId(productEntityExt.getId());
        purchaseProductEntity.setParentId(productEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
        purchaseProductEntity.setProductName(I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE) + XbbRefTypeEnum.PRODUCT.getName());
        purchaseProductEntity.setProductNo(productEntityExt.getSerialNo());
        purchaseProductEntity.setProductSpecification("");
        purchaseProductEntity.setProductUnit("");
        purchaseProductEntity.setProductPrice(0D);
        purchaseProductEntity.setBarcode("1.0");
        purchaseProductEntity.setMemo("");
        purchaseProductEntity.setProductNo("23");
        purchaseProductEntity.setDiscount(0D);
        purchaseProductEntity.setOtherCharge(0D);
        purchaseProductEntity.setSort(1);
        purchaseProductEntity.setMoney(2D);
        purchaseProductEntity.setAddTime(DateTimeUtil.getInt());
        purchaseProductEntity.setUpdateTime(DateTimeUtil.getInt());
        purchaseProductEntity.setDel(0);
        for (PurchaseEntityExt purchaseEntity : insertList){
            purchaseProductEntity.setId(null);
            purchaseProductEntity.setPurchaseSheetId(purchaseEntity.getId());
            purchaseProductModel.insert(purchaseProductEntity);
        }
        return "";
    }

    private String generateWaitOutstockData(GenerateDataDTO generateDataDTO, Long dataSize, long addTime, long updateTime, long nowTime) throws XbbException {
        String corpid = generateDataDTO.getCorpid();
        ContractEntityExt contractEntity = contractModel.getByKey(generateDataDTO.getDataId(),corpid);
        if (Objects.isNull(contractEntity)) {
            return "dataId对应的合同不存在";
        }
        List<ContractEntityExt> insertList = new ArrayList<>();
        for (int i = 0;i <dataSize;i++){
            ContractEntityExt entityExt = new ContractEntityExt();
            BeanUtil.copyProperties(contractEntity,entityExt);
            entityExt.setId(null);
            entityExt.setAddTime(addTime);
            entityExt.setUpdateTime(updateTime);
            contractModel.insert(entityExt);
            insertList.add(entityExt);
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery("del",0));
        boolQueryBuilder.filter(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID),generateDataDTO.getProductId()));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 1);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ProductEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,ProductEntityExt.class);
        ProductEntityExt productEntityExt = esEntities.getContent().get(0);
        ContractProductEntity contractProductEntity = new ContractProductEntity();
        contractProductEntity.setCorpid(corpid);
        contractProductEntity.setProductNum(1D);
        contractProductEntity.setIsProduce(0);
        contractProductEntity.setProductId(productEntityExt.getId());
        contractProductEntity.setParentId(productEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
        contractProductEntity.setProductName(I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE) + XbbRefTypeEnum.PRODUCT.getName());
        contractProductEntity.setProductNo(productEntityExt.getSerialNo());
        contractProductEntity.setAddTime(DateTimeUtil.getInt());
        contractProductEntity.setUpdateTime(DateTimeUtil.getInt());
        for (ContractEntityExt contractEntityExt : insertList){
            contractProductEntity.setId(null);
            contractProductEntity.setContractId(contractEntityExt.getId());
            contractProductModel.insert(contractProductEntity);
        }
        return "";
    }

    private String generateWaitPurchaseData(GenerateDataDTO generateDataDTO, Long dataSize, long addTime, long updateTime, long nowTime, Integer isProduce) throws XbbException {
        String corpid = generateDataDTO.getCorpid();
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        BomBillEntityExt bomBillEntity = bomBillModel.getByKey(generateDataDTO.getBomId(), corpid);
        if (Objects.isNull(bomBillEntity)) {
            return "bomId对应的bom单不存在";
        }
        Long bomId = bomBillEntity.getId();
        param.put("corpid",corpid);
        param.put("del",0);
        param.put("type",1);
        param.put("bomId",bomId);
        List<BomProductEntity> bomProductEntityList = bomProductModel.findEntitys(param);
        if (Objects.isNull(bomProductEntityList) || bomProductEntityList.isEmpty()) {
            return "bom单没有产品";
        }
        BomProductEntity bomProductEntity = bomProductEntityList.get(0);
        List<ContractEntityExt> insertList = new ArrayList<>();
        ContractEntityExt contractEntity = contractModel.getByKey(generateDataDTO.getDataId(),corpid);
        if (Objects.isNull(contractEntity)) {
            return "dataId对就的待采购合同不存在";
        }
        for (int i = 0;i <dataSize;i++){
            ContractEntityExt entityExt = new ContractEntityExt();
            BeanUtil.copyProperties(contractEntity,entityExt);
            entityExt.setId(null);
            entityExt.setAddTime(addTime);
            entityExt.setUpdateTime(updateTime);
            contractModel.insert(entityExt);
            insertList.add(entityExt);
        }
        ContractProductEntity contractProductEntity = new ContractProductEntity();
        contractProductEntity.setCorpid(corpid);
        contractProductEntity.setProductNum(1000000000D);
        contractProductEntity.setIsProduce(isProduce);
        contractProductEntity.setProductId(bomProductEntity.getProductId());
        contractProductEntity.setParentId(bomProductEntity.getParentId());
        contractProductEntity.setProductName(bomProductEntity.getProductName());
        contractProductEntity.setProductNo(bomProductEntity.getProductNo());
        contractProductEntity.setAddTime(DateTimeUtil.getInt());
        contractProductEntity.setType(ContractProductTypeEnum.CONTNRACT.getCode());
        contractProductEntity.setUpdateTime(DateTimeUtil.getInt());
        for (ContractEntityExt contractEntityExt : insertList){
            contractProductEntity.setId(null);
            contractProductEntity.setContractId(contractEntityExt.getId());
            contractProductModel.insert(contractProductEntity);
        }
        return "";
    }

    private String generateCustomerData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long lastConnectTime = (generateDataDTO.getLastConnectTime() == null || Objects.equals(generateDataDTO.getLastConnectTime(), 0L)) ?
                0L : nowTime + generateDataDTO.getLastConnectTime() * TimeConstant.SECONDS_PER_DAY;
        String birthday = generateDataDTO.getBirthday() == null ? "2019-12-01" : generateDataDTO.getBirthday();


        String returnStr = "";

        try {

            CustomerEntityExt customerEntityExt = customerModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(customerEntityExt)) {
                return "dataId对应的客户不存在";
            }
            List<PaasFormDataEntity> list = new ArrayList<>();
            // 需要改变的字段：创建时间、最后跟进时间、客户生日、手机号（固定号码，好发送短信）
            for (int i = 1; i <= dataSize; i++) {
                CustomerEntityExt entityExt = new CustomerEntityExt();
                BeanUtil.copyProperties(customerEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String name = data.getString(CustomerManagementEnum.NAME.getAttr());
                String shortName = data.getString(CustomerManagementEnum.NAME_SHORT.getAttr());
                data.put(CustomerManagementEnum.NAME.getAttr(), name  + i);
                data.put(CustomerManagementEnum.NAME_SHORT.getAttr(), shortName + i);

                // 电话
                if (data.containsKey(CustomerManagementEnum.PHONE.getAttr())) {
                    JSONArray phone = new JSONArray();
                    JSONObject jsonObject = new JSONObject();
                    String phoneNum = "13643806682";
                    jsonObject.put("text_2", phoneNum);
                    phone.add(jsonObject);
                    data.put(CustomerManagementEnum.PHONE.getAttr(), phone);
                }

                int max = 2;
                int min = 0;
                int random = (int) (Math.random() * (max - min + 1)) + min;
                data.put(CustomerManagementEnum.GENRE.getAttr(), random);
                data.put(CustomerManagementEnum.TYPE.getAttr(), random);
                data.put(CustomerManagementEnum.IS_INDIVIDUAL.getAttr(), random);
                data.put(CustomerManagementEnum.SCALE.getAttr(), random);
                data.put(CustomerManagementEnum.INDUSTRY.getAttr(), random);
                data.put(CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(), random);
                // 生日
                if (data.containsKey(CustomerManagementEnum.BIRTHDAY.getAttr())) {
                    data.put(CustomerManagementEnum.BIRTHDAY.getAttr(), birthday);
                    data.put(CustomerManagementEnum.BIRTHDAY_FLAG.getAttr(), 1);
                    data.put(CustomerManagementEnum.BIRTHDAY_MMDD.getAttr(), DateTimeUtil.getString(DateTimeUtil.getDate(birthday, DateTimeUtil.SDFDate), DateTimeUtil.SDFMonthDay));
                }
                // 最后联系时间
                data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), lastConnectTime);

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);


                list.add(entityExt);
            }
            customerModel.insertBatch(list, false);
        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }


    private String generateOpportunityData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long lastConnectTime = (generateDataDTO.getLastConnectTime() == null || Objects.equals(generateDataDTO.getLastConnectTime(), 0L)) ?
                0L : nowTime + generateDataDTO.getLastConnectTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(opportunityEntityExt)) {
                return "dataId对应的机会不存在";
            }
            boolean isNoWorkOrProportionEqualsZero = false;
            SaleStageEntity stageStage = null;
            if (StringUtil.isNotEmpty(generateDataDTO.getSaleStage())) {
                stageStage = saleStageModel.getByCode(opportunityEntityExt.getCorpid(), opportunityEntityExt.getFormId(), generateDataDTO.getSaleStage());
                if (Objects.nonNull(stageStage)) {
                    isNoWorkOrProportionEqualsZero = stageWorkModel.isNoWorkOrProportionEqualsZero(opportunityEntityExt.getCorpid(), opportunityEntityExt.getFormId(), stageStage.getStageProcessId(), stageStage.getId(), XbbRefTypeEnum.SALE_STAGE.getCode(), SaasMarkEnum.SAAS.getCode());
                }
            }
            // 需要改变的字段：最后跟进时间、机会阶段
            for (int i = 1; i <= dataSize; i++) {
                OpportunityEntityExt entityExt = new OpportunityEntityExt();
                BeanUtil.copyProperties(opportunityEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String name = data.getString(SalesOpportunityEnum.NAME.getAttr());
                data.put(SalesOpportunityEnum.NAME.getAttr(), name + i);

                // 最后联系时间
                data.put(SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr(), lastConnectTime);
                // 阶段值
                if (Objects.nonNull(stageStage)) {
                    data.put(SalesOpportunityEnum.SALE_STAGE.getAttr(), stageStage.getCode());
                    data.put(SalesOpportunityEnum.STAGE_PROCESS_ID.getAttr(), stageStage.getStageProcessId());
                    data.put(SalesOpportunityEnum.STAGE_ID.getAttr(), stageStage.getId());
                    data.put(SalesOpportunityEnum.STAGE_RATIO.getAttr(), isNoWorkOrProportionEqualsZero ? stageStage.getOutProportion() : stageStage.getIntoProportion());
                } else {
                    data.remove(SalesOpportunityEnum.SALE_STAGE.getAttr());
                    data.remove(SalesOpportunityEnum.STAGE_PROCESS_ID.getAttr());
                    data.remove(SalesOpportunityEnum.STAGE_ID.getAttr());
                    data.remove(SalesOpportunityEnum.STAGE_RATIO.getAttr());
                }

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                opportunityModel.insert(entityExt);
                if (Objects.nonNull(stageStage)) {
                    // 保存销售机会阶段记录
                    OpportunityStageLogEntity saleStageLog = new OpportunityStageLogEntity();
                    saleStageLog.setCorpid(entityExt.getCorpid());
                    saleStageLog.setFormId(entityExt.getFormId());
                    saleStageLog.setDataId(entityExt.getId());
                    saleStageLog.setStageCode(stageStage.getCode());
                    saleStageLog.setIsNow(1);
                    saleStageLog.setIntoTime(DateTimeUtil.getInt());
                    saleStageLog.setOutTime(0L);
                    saleStageLog.setAddTime(DateTimeUtil.getInt());
                    saleStageLog.setUpdateTime(DateTimeUtil.getInt());
                    saleStageLog.setDel(0);
                    saleStageLog.setStageProcessId(stageStage.getStageProcessId());
                    saleStageLog.setStageId(stageStage.getId());
                    saleStageLog.setStageType(stageStage.getType());
                    opportunityStageLogModel.save(saleStageLog);
                }
            }

        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generateContractData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long deadLine = generateDataDTO.getDeadLine() == null ? nowTime + TimeConstant.SECONDS_PER_WEEK : nowTime + generateDataDTO.getDeadLine() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            ContractEntityExt contractEntityExt = contractModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(contractEntityExt)) {
                return "dataId对应的合同不存在";
            }
            // 需要改变的字段：添加时间、合同到期日期
            for (int i = 1; i <= dataSize; i++) {
                ContractEntityExt entityExt = new ContractEntityExt();
                BeanUtil.copyProperties(contractEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String name = data.getString(ContractEnum.NAME.getAttr());
                data.put(ContractEnum.NAME.getAttr(), name + i);
                data.put(ContractEnum.DEADLINE.getAttr(), deadLine);

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                 contractModel.insert(entityExt);
            }

        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generatePaymentData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long estimateTime = generateDataDTO.getEstimateTime() == null ? nowTime + TimeConstant.SECONDS_PER_WEEK : nowTime + generateDataDTO.getEstimateTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            PaymentEntityExt paymentEntityExt = paymentModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(paymentEntityExt)) {
                return "dataId对应的应收款不存在";
            }
            List<PaymentEntityExt> list = new ArrayList<>();
            // 需要改变的字段：预计到期时间
            for (int i = 1; i <= dataSize; i++) {
                PaymentEntityExt entityExt = new PaymentEntityExt();
                BeanUtil.copyProperties(paymentEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String paymentNo = entityExt.getSerialNo();
                entityExt.setSerialNo(paymentNo + i);

                data.put(PaymentEnum.ESTIMATE_TIME.getAttr(), estimateTime);
                data.put(PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);
                list.add(entityExt);
            }
            paymentModel.insertBatch(list);
        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generatePayPlanData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long estimateTime = generateDataDTO.getEstimateTime() == null ? nowTime + TimeConstant.SECONDS_PER_WEEK : nowTime + generateDataDTO.getEstimateTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            PayPlanEntityExt payPlanEntityExt = payPlanModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(payPlanEntityExt)) {
                return "dataId对应的付款计划不存在";
            }
            List<PayPlanEntityExt> list = new ArrayList<>();
            // 需要改变的字段：预计到期时间
            for (int i = 1; i <= dataSize; i++) {
                PayPlanEntityExt entityExt = new PayPlanEntityExt();
                BeanUtil.copyProperties(payPlanEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String payPlanNo = entityExt.getSerialNo();
                entityExt.setSerialNo(payPlanNo + i);

                data.put(PayPlanEnum.ESTIMATE_TIME.getAttr(), estimateTime);
                data.put(PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                list.add(entityExt);
            }
            payPlanModel.insertBatch(list);
        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generateSupplierData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long lastConnectTime = (generateDataDTO.getLastConnectTime() == null || Objects.equals(generateDataDTO.getLastConnectTime(), 0L)) ?
                0L : nowTime + generateDataDTO.getLastConnectTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            SupplierEntityExt supplierEntityExt = supplierModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(supplierEntityExt)) {
                return "dataId对应的供应商不存在";
            }
            // 需要改变的字段：添加时间、最后跟进时间
            for (int i = 1; i <= dataSize; i++) {
                SupplierEntityExt entityExt = new SupplierEntityExt();
                BeanUtil.copyProperties(supplierEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String name = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                data.put(SupplierEnum.SUPPLIER_NAME.getAttr(), name + i);

                data.put(SupplierEnum.LAST_CONNECT_TIME.getAttr(), lastConnectTime);

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                supplierModel.insert(entityExt);
            }

        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generatePurchaseData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long estimateArriveTime = generateDataDTO.getEstimateArriveTime() == null ? nowTime + TimeConstant.SECONDS_PER_WEEK : nowTime + generateDataDTO.getEstimateArriveTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(purchaseEntityExt)) {
                return "dataId对应的采购合同不存在";
            }
            // 需要改变的字段：添加时间、到货时间
            for (int i = 1; i <= dataSize; i++) {
                PurchaseEntityExt entityExt = new PurchaseEntityExt();
                BeanUtil.copyProperties(purchaseEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String serialNo = entityExt.getSerialNo();
                entityExt.setSerialNo(serialNo + i);

                String name = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                data.put(PurchaseEnum.PURCHASE_NAME.getAttr(), name + i);

                data.put(PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr(), estimateArriveTime);

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                purchaseModel.insert(entityExt);
            }

        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generateProductionOrderData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {

        // 参数
        long planTime = generateDataDTO.getPlanTime() == null ? nowTime + TimeConstant.SECONDS_PER_WEEK : nowTime + generateDataDTO.getPlanTime() * TimeConstant.SECONDS_PER_DAY;

        String returnStr = "";
        try {
            ProductionOrderEntityExt productionOrderEntityExt = productionOrderModel.getByKey(generateDataDTO.getDataId(), generateDataDTO.getCorpid());
            if (Objects.isNull(productionOrderEntityExt)) {
                return "dataId对应的生产单不存在";
            }
            // 需要改变的字段：计划完成日期
            for (int i = 1; i <= dataSize; i++) {
                ProductionOrderEntityExt entityExt = new ProductionOrderEntityExt();
                BeanUtil.copyProperties(productionOrderEntityExt, entityExt);
                JSONObject data = entityExt.getData();
                String sheetNo = entityExt.getSerialNo();
                entityExt.setSerialNo(sheetNo + i);

                data.put(ProductionOrderEnum.PLAN_TIME.getAttr(), planTime);

                entityExt.setData(data);
                entityExt.setId(null);

                entityExt.setAddTime(addTime);
                entityExt.setUpdateTime(updateTime);

                productionOrderModel.insert(entityExt);
            }

        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }

    private String generateProductData(GenerateDataDTO generateDataDTO, Long dataSize, Long addTime, Long updateTime, Long nowTime) {
        // 参数
        String corpid = generateDataDTO.getCorpid();
        String returnStr = "";
        try {
            ProductEntityExt entity = productModel.getByKey(generateDataDTO.getDataId(), corpid);
            if (Objects.isNull(entity)) {
                return "dataId对应的产品不存在";
            }
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID),generateDataDTO.getDataId()));
            List<ProductEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,ProductEntityExt.class,null);
            if (Objects.isNull(paasFormDataEntityExtList) || paasFormDataEntityExtList.isEmpty()) {
                return "dataId没有对应的子产品";
            }
            List<ProductEntityExt> list = new ArrayList<>();

            // 需要改变的字段：添加时间、合同到期日期
            for (int i = 1; i <= dataSize; i++) {
                ProductEntityExt parentProduct = new ProductEntityExt();
                BeanUtil.copyProperties(entity,parentProduct);
                Double randomStock = ((Math.random() * System.currentTimeMillis()) % 100);
                JSONObject data = parentProduct.getData();
                String name = data.getString(ProductEnum.NAME.getAttr());
                data.put(ProductEnum.NAME.getAttr(), name + i);
                data.put(ProductEnum.STOCK.getAttr(),randomStock);
                data.put(ProductEnum.STOCK_LOWER_LIMIT.getAttr(),10D);
                data.put(ProductEnum.STOCK_UPPER_LIMIT.getAttr(),20D);
                data.put(ProductEnum.IS_NOTIFY.getAttr(),1);
                parentProduct.setData(data);
                parentProduct.setId(null);
                parentProduct.setAddTime(addTime);
                Long time = updateTime + i;
                parentProduct.setUpdateTime(time);
                list.add(parentProduct);
            }
            //父产品保存
            productModel.insertBatch(list);
            List<ProductEntityExt> childList = new ArrayList<>();
            List<Long> parentIdList = new ArrayList<>();
            List<ProductEntityExt> fistSkuList = new ArrayList<>();
            for (ProductEntityExt productEntityExt : list) {
                int index = 0;
                for (ProductEntityExt entityExt : paasFormDataEntityExtList){
                    ProductEntityExt childProduct = new ProductEntityExt();
                    BeanUtil.copyProperties(entityExt,childProduct);
                    JSONObject childData = childProduct.getData();
                    childData.put(ProductEnum.STOCK.getAttr(),productEntityExt.getData().getDouble(ProductEnum.STOCK.getAttr()));
                    childData.put(ProductEnum.STOCK_LOWER_LIMIT.getAttr(),30D);
                    childData.put(ProductEnum.STOCK_UPPER_LIMIT.getAttr(),70D);
                    childData.put(ProductEnum.IS_NOTIFY.getAttr(),1);
                    childData.put(ProductEnum.PARENT_ID.getAttr(),productEntityExt.getId());
                    childProduct.setData(childData);
                    childProduct.setId(null);
                    childProduct.setAddTime(addTime);
                    childProduct.setUpdateTime(updateTime);
                    childList.add(childProduct);
                    if (index == 0){
                        fistSkuList.add(childProduct);
                    }
                    index++;
                }
                parentIdList.add(productEntityExt.getId());
            }
            //子产品保存
            productModel.insertBatch(childList);
            Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid",corpid);
            param.put("del",0);
            param.put("productId",generateDataDTO.getDataId());
            List<SpecificationEntity> specificationEntityList = specificationModel.findEntitys(param);
            for (Long parentId : parentIdList){
                for (SpecificationEntity specificationEntity : specificationEntityList){
                    specificationEntity.setId(null);
                    specificationEntity.setProductId(parentId);
                }
            }
            //规格保存
            if (!specificationEntityList.isEmpty()){
                specificationModel.insertBatch(specificationEntityList);
            }
            param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid",corpid);
            param.put("del",0);
            param.put("pageSize",1);
            List<WarehouseEntityExt> warehouseEntityExts = warehouseModel.findEntitys(param);
            List<ProductWarehouseEntity> productWarehouseEntityList = new ArrayList<>();
            List<ProductStockEntity> productStockEntityList = new ArrayList<>();
            if (!warehouseEntityExts.isEmpty()){
                Long warehouseId = warehouseEntityExts.get(0).getId();
                for (ProductEntityExt entityExt : fistSkuList) {
                    Long parentId = entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                    Double stock = entityExt.getData().getDouble(ProductEnum.STOCK.getAttr());
                    ProductWarehouseEntity productWarehouseEntity = new ProductWarehouseEntity();
                    productWarehouseEntity.setCorpid(corpid);
                    productWarehouseEntity.setWarehouseId(warehouseId);
                    productWarehouseEntity.setWarehouseName(warehouseEntityExts.get(0).getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                    productWarehouseEntity.setParentId(parentId);
                    productWarehouseEntity.setProductId(entityExt.getId());
                    productWarehouseEntity.setNum(stock);
                    productWarehouseEntity.setIsNotify(1);
                    productWarehouseEntity.setStockLowerLimit(40D);
                    productWarehouseEntity.setStockUpperLimit(550D);
                    productWarehouseEntity.setCost(0D);
                    productWarehouseEntity.setTotalCost(0D);
                    productWarehouseEntity.setWarehouseChecked(1);
                    productWarehouseEntity.setAddTime(DateTimeUtil.getInt());
                    productWarehouseEntity.setUpdateTime(DateTimeUtil.getInt());
                    productWarehouseEntity.setWarehouseKey(productWarehouseEntity.getProductId() + "_" + productWarehouseEntity.getWarehouseId());
                    productWarehouseEntityList.add(productWarehouseEntity);

                    ProductStockEntity productStockEntity = new ProductStockEntity();
                    productStockEntity.setCorpid(corpid);
                    productStockEntity.setParentId(parentId);
                    productStockEntity.setProductId(entityExt.getId());
                    productStockEntity.setWarehouseId(warehouseId);
                    productStockEntity.setWarehouseName(warehouseEntityExts.get(0).getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                    productStockEntity.setNum(stock);
                    productStockEntity.setBatch("pici");
                    productStockEntity.setProduceDate(DateTimeUtil.getTodayInt());
                    productStockEntity.setGuaranteePeriod(generateDataDTO.getGuaranteePeriod() * TimeConstant.SECONDS_PER_DAY);
                    productStockEntity.setCost(0D);
                    productStockEntity.setAddTime(DateTimeUtil.getInt());
                    productStockEntity.setUpdateTime(DateTimeUtil.getInt());
                    productStockEntity.setDel(DelEnum.NORMAL.getDel());
                    productStockEntity.setWarehouseChecked(1);
                    productStockEntityList.add(productStockEntity);
                    productStockEntity.setBatchKey(productStockEntity.getBatch() + "_" + productStockEntity.getWarehouseId() + "_" + productStockEntity.getBatch() + "_" + productStockEntity.getProduceDate() + "_" + productStockEntity.getGuaranteePeriod());
                    productStockEntity.setTotalCost(Arith.mul(productStockEntity.getNum(),productStockEntity.getCost()));
                }
                if (!productWarehouseEntityList.isEmpty()){
                    productWarehouseModel.insertBatch(productWarehouseEntityList);
                }
                if (!productStockEntityList.isEmpty()){
                    productStockModel.insertBatch(productStockEntityList);
                }
            }
        } catch (Exception e) {
            LOG.error("模拟数据报错", e);
            returnStr = "插入数据失败";
        }
        return returnStr;
    }
}
